using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Calais
{
    [Serializable]
    public class CalaisWebServiceException : Exception
    {
        private XDocument _doc;
        private XElement _elem;
        public string _message;

        public CalaisWebServiceException(XDocument doc)
        {
            _doc = doc;
            base.Source = _doc.ToString();
            base.HelpLink = "http://www.opencalais.com/";
        }

        public override string Message
        {
            get
            {
                if (_doc.Descendants("Exception") != null)
                {
                    _elem = _doc.Descendants("Exception").First();
                }
                else
                {
                    return "The OpenCalais web service raised an unknown exception.";
                }

                return string.Format(" The OpenCalais web service raised an exception: {0}.", _elem.Value);    
            }
        }   

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            
            if(_doc.Descendants("Exception") != null)
            {
                _elem = _doc.Descendants("Exception").First();
            }

            sb.AppendFormat(" The OpenCalais web service raised an exception: {0} ", _elem.Value);

            if (this.InnerException != null)
            {
                sb.AppendFormat(" ---> {0} <---", base.InnerException.ToString());
            }

            if (this.StackTrace != null)
            {
                sb.Append(Environment.NewLine);
                sb.Append(base.StackTrace);
            }

            return sb.ToString();
        }
    }
}